// hyb_yl/pharmacy/pages/distribution/distribution.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab_index: 2,
    price: '',
    addresslist: [],
    repicelist: [],
    addbox: true,
    medicbox: true,
    num: 1,
    price: '', //单价
    sum: '', //总价
    frieght: 6, // 运费
    sales: 0.40, //退货
    invoice: true, //发票
    electron: ["电子发票"],
    invoiceTitle: ["个人", "单位"], //发票抬头
    unitName: '', //单位名称
    ratepayer: '', //纳税号
    invoiceIndex: 0,
    invoiceCont: ["明细", "不开发票"], //发票内容
    partIndex: 1, //选择发票内容下标
    coupon: true, //优惠券初始值
    couponTitle: [{
      usable: 0,
      title: "可用优惠券"
    },
    {
      usable: 1,
      title: "不可用优惠券"
    }
    ], //选择可用优惠和不可用优惠
    couponIndex: 0,
    instru: true,
    already: [],
    arr: [],
    favorable: '', //优惠价格
    commodity: [],
    druglist: true,
    countmoney: 0,
    summoney: 0,
    // 总重
    feight: 0,
    statu: 1,
    telphone:"",
    addressId:"",
    goodstype:'',
    // 是否自提
  },
  tab_chose: function (e) {
    console.log(e.currentTarget.dataset.index)
    var index = e.currentTarget.dataset.index;
    this.setData({
      tab_index: index
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var carlist = wx.getStorageSync('shopcar')
    var that = this;
    var from = options.from;
    that.setData({
      from:from
    })
    if(from == 'hos_detail')
    {
      var carlist = wx.getStorageSync('shopcar')
    }else if(from == 'car')
    {
      var carlist = wx.getStorageSync('car_list')
    }else if(from == 'goods_detail')
    {
      var carlist = wx.getStorageSync('goods')
    }
    console.log(carlist)
    var g_kuaidi = carlist[0].g_kuaidi
    var ifcfy = carlist[0].ifcfy
    var ifcf = carlist[0].ifcf
    var mostgt = carlist[0].mostgt
    var gg_id = carlist[0].gg_id
    var goodstype = carlist[0].goodstype
    that.setData({
      carlist: carlist,
      g_kuaidi: g_kuaidi,
      mostgt: mostgt,
      ifcfy: ifcfy,
      gg_id: gg_id,
      ifcf: ifcf,
      goodstype: goodstype
    })
    that.getHospital()
    that.getsum()
    var already = wx.getStorageSync("coupon")
    var address = wx.getStorageSync("Address")
    that.setData({
      addresslist: address,
      already: already,
      addressid: address.addressId
    })
    if (that.data.addresslist == "") {
      that.setData({
        addbox: true
      })
    } else {
      that.setData({
        addbox: false
      })
    }
    var medicemess = wx.getStorageSync("medicemess")

    var repicelist = medicemess.slice(0, 1)
    that.setData({
      repicelist: repicelist
    })
    if (that.data.ifcf == "1") {
      that.setData({
        medicbox: true
      })
    } else {
      that.setData({
        medicbox: false
      })
    }
  },
  getHospital:function(res){
    var that = this;
    console.log(that.data.carlist[0]);
    app.util.request({
      'url':"entry/wxapp/user.hospital_det",
      data:{
        id:that.data.carlist[0].sid,
      },
      success:function(res){
        that.setData({
          hospital:res.data,
        })
      }
    })
  },
  getsum() {
    var commodity = this.data.carlist;
    var summoney = this.data.summoney
    var countmoney = 0
    var feight = 0
    var g_kuaidi = 0
    var a = 0
    for (var i = 0; i < commodity.length; i++) {
      feight += parseFloat((commodity[i].num * commodity[i].gg_ke).toFixed(3))
      countmoney += parseFloat((commodity[i].num * commodity[i].smoney).toFixed(2))
      g_kuaidi = commodity[i].g_kuaidi
    }
    feight = parseFloat(feight).toFixed(3)
    countmoney = parseFloat(countmoney).toFixed(2)
    summoney = (parseFloat(countmoney) + parseFloat(g_kuaidi)).toFixed(2)

    this.setData({
      feight: feight,
      countmoney: countmoney,
      g_kuaidi: g_kuaidi,
      summoney: summoney
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var already = wx.getStorageSync("coupon")
    var address = wx.getStorageSync("Address")
    this.setData({
      already: already,
      addressid: address.addressId,
    })
    var medicemess = wx.getStorageSync("medicemess")
    var repicelist = medicemess.slice(0, 1)
    this.setData({
      repicelist: repicelist
    })
    if (repicelist == "") {
      this.setData({
        medicbox: true
      })
    } else {
      this.setData({
        medicbox: false
      })
    }
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    var that = this
    console.log(currPage.data.conets)
    if (currPage.data.conets) {
      var typedate = currPage.data.typedate
      var conets = currPage.data.conets
      if (typedate == '1') {
        that.setData({
          medicbox: false
        })
      } else {
        that.setData({
          medicbox: true
        })
      }
      that.setData({
        typedate: typedate,
        conets: conets
      })
    }
    if (currPage.data.j_id) {
      var that = this
      var j_id = currPage.data.j_id
      app.util.request({
        'url': 'entry/wxapp/user.detailmyjd',
        data: {
          j_id: j_id
        },
        success: function (res) {
          console.log(res)
          that.setData({
            age: res.data.age,
            sex: res.data.sex,
            phone: res.data.tel,
            username: res.data.names,
            medicbox: false,
            cf_id: currPage.data.cf_id
          })
        }
      })

    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var medicemess = wx.getStorageSync("medicemess")
    var repicelist = medicemess.slice(0, 1)
    this.setData({
      repicelist: repicelist
    })
    if (repicelist == "") {

    } else {
      this.setData({
        medicbox: false
      })
    }
  },
  changetelphone:function(e){
    this.setData({
      telphone:e.detail.value
    })
  },
  submit: function (e) {
    console.log(e)
    var that = this
    var that = this
    var conets = that.data.conets
    var tab_index = that.data.tab_index
    var ifcf = that.data.ifcf
    var goodstype = that.data.goodstype
    if (tab_index==2) {
      var mode = 1
    } else {
      var mode = 0
    }

    var tab_index = that.data.tab_index;
    var telphone = that.data.telphone;
    if (tab_index == 3 && that.data.addresslist == "" && !that.data.switchChecked) {
      wx.showToast({
        title: '请先填写收货地址',
        icon: 'none'
      })
    } else if (that.data.medicbox && that.data.ifcfy == 1) {
      wx.showToast({
        title: '请先填写处方信息',
        icon: 'none'
      })
    }else if(that.data.tab_index == 2 && telphone == ''){
      wx.showToast({
        title: '请填写电话',
        icon:"none"
      })
    } else {
      var commodity = that.data.carlist
      // var g_kuaidi = commodity.g_kuaidi //运费
      // var gg_id = commodity.gg_id //规格id
      // var sid = commodity.sid //商品id
      var countmoney = e.currentTarget.dataset.countmoney //商品金额
      var feight = e.currentTarget.dataset.feight
      var num = e.currentTarget.dataset.num
      var summoney = e.currentTarget.dataset.summoney //进行各种折扣之后的金额
      var u_id = e.currentTarget.dataset.u_id
      var totalMoney = that.data.totalMoney //实际金额
      var deliverMoney = that.data.deliverMoney //运费
      var addressid = that.data.addressid
      console.log(addressid)
      //支付
      app.util.request({
        'url': 'entry/wxapp/goods.creatorder',
        data: {
          // g_kuaidi: g_kuaidi,
          // gg_id: gg_id,
          mode: mode,
          ifcf: that.data.ifcfy,
          ifshop: 0,
          conets: conets,
          goodarr: commodity,
          countmoney: countmoney,
          feight: feight,
          num: num,
          realTotalMoney: summoney,
          totalMoney: countmoney,
          deliverMoney: deliverMoney,
          u_id: u_id,
          addressid: addressid,
          openid: wx.getStorageSync('openid'),
          goodstype: goodstype,
          telphone:telphone,
          tab_index:that.data.tab_index
        },
        success: function (res) {
          console.log(res)
          wx.setStorageSync('shopcar', '')
          var orders = res.data
          //生成订单二维码
          app.util.request({
            'url': 'entry/wxapp/Studio.goodserweima',
            data: {
              orders: orders,
            },
            success: function (res) {
              console.log(res)
            },
          })
          app.util.request({
            'url': 'entry/wxapp/yuyue.paycforder',
            header: {
              "Content-Type": "application/xml"
            },
            method: "GET",
            data: {
              openid: wx.getStorageSync('openid'),
              z_tw_money: countmoney,
              orders: orders
            },
            success: function (res) {
              console.log(res);
              wx.requestPayment({
                'timeStamp': res.data.timeStamp,
                'nonceStr': res.data.nonceStr, //字符串随机数
                'package': res.data.package,
                'signType': res.data.signType,
                'paySign': res.data.paySign,
                success: function (res) {
                  console.log(res)
                  
                  wx.reLaunch({
                    url: '/hyb_yl/userCommunicate/pages/order/order',
                  })
                },
                fail: function () {
                  wx.reLaunch({
                    url: '/hyb_yl/userCommunicate/pages/order/order',
                  })
                }
              })
            }
          })
        }
      })
    }

  },
  address: function () {
    console.log(1)
    var region = [];
    var arr1 = [];
    var that = this
    wx.chooseAddress({
      success: function (res) {
        console.log("res")
        console.log(res)
        console.log(JSON.stringify(res))
        var name = res.userName
        var phone = res.telNumber
        region.push(res.provinceName, res.cityName, res.countyName)
        var address = res.detailInfo
        var addlist = {
          name: res.userName,
          phone: res.telNumber,
          address: res.detailInfo,
          region: region,
          label: -1,
          addlabel: ""
        }
        console.log(addlist)
        //添加收货人信息
        var userName = addlist.name
        var userPhone = addlist.phone
        var userAddress = addlist.region[0] + '-' + addlist.region[1] + '-' + addlist.region[2] + '-' + addlist.address
        app.util.request({
          'url': 'entry/wxapp/goods.creatuseraddress',
          data: {
            openid: wx.getStorageSync('openid'),
            userName: userName,
            userPhone: userPhone,
            userAddress: userAddress
          },
          success: function (res) {
            console.log(res)
            var addressid = res.data.addressId
            wx.setStorageSync("Address", res.data)
            that.setData({
              addressid: addressid,
              addresslist: res.data
            })
            if (res.data == "") {
              that.setData({
                addbox: true
              })
            } else {
              that.setData({
                addbox: false
              })
            }
          }
        })
        arr1 = wx.getStorageSync("Address") || [];
        that.setData({
          addresslist: arr1
        })
      },
      fail: function (err) {
        that.openConfirm()


      }
    })
  },
  openConfirm: function () {
    wx.showModal({
      content: '检测到您没打开地址权限，是否去设置打开？',
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              console.log(res)
            } //打开设置面板
          })
        } else {
          console.log('用户点击取消')
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})